import { publicRoutes } from '@/router'
import { defineStore } from 'pinia'
import {isNotEmpty} from "@/utils/validate";
import AdminLayout from '@/layout/admin/index.vue'

/**
 * vite无法在这里使用 component = () => import('@/views/index.vue')
 * 只能如下赋值
 * let views = import.meta.glob('@/views/**.vue')
 * let component = views['@/views/index.vue']
 */
const views = import.meta.glob('@/views/**/*.vue')

/**
 * 将后端传过来的菜单信息，转化为路由
 *
 * @param menuList
 */
function createRoutes(menuList){
  let routes = []
  menuList.forEach(menu =>{
    let route = {
      path: menu.menuPath,
      name: menu.menuName,
      meta: {
        title: menu.menuTitle,
        icon: menu.menuIcon
      }
    }
    // 如果配置的component是admin，说明该路由是父级菜单，组件是AdminLayout组件,
    // 并将子路由的第一个路由设为默认重定向
    if (menu.component === 'admin'){
      route.component = AdminLayout
      route.redirect = menu.children[0].menuPath
    }else {
      route.component = views[`/src/views${menu.component}.vue`]
    }
    // 过滤子路由
    if (isNotEmpty(menu.children)){
      route.children = createRoutes(menu.children)
    }
    routes.push(route)
  })
  return routes
}

const PermissionStore = defineStore({
  id: 'permission',
  state: () => ({
    routes: [],
    addRoutes: [],
  }),
  actions: {
    setRoutes(routes) {
      this.addRoutes = routes
      this.routes = publicRoutes.concat(routes)
    },
    // 初始化后端传过来的路由信息
    generateRoutes(menuList) {
      return new Promise((resolve) => {
        let accessedRoutes = createRoutes(menuList)
        accessedRoutes.push({ path: '/:pathMatch(.*)*', redirect: '/404', name: 'all', hidden: true })
        this.setRoutes(accessedRoutes)
        resolve(accessedRoutes)
      })
    },
  },
})

export default PermissionStore
